package com.starbaba.system.syscode.service;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.starbaba.core.hibernate.DAOFactory;
import com.starbaba.core.service.CommonServiceSupport;
import com.starbaba.system.syscode.model.SyscodeVO;

@SuppressWarnings({ "serial", "unchecked" })
@Component
public class SyscodeServiceImpl extends CommonServiceSupport implements
		SyscodeService {

	/**
	 * 查询 type <> '*' 信息
	 * 
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<SyscodeVO> doFindSyscodeVOByType(String type) throws Exception {
		return DAOFactory.getInstance().getSessionFactory().getCurrentSession()
				.createCriteria(SyscodeVO.class)
				.add(Restrictions.eq("type", type))
				.add(Restrictions.ne("code", -1)).list();
	}

	/**
	 * 查询 type <> '*' 信息
	 * @param type
	 * @param neCode 过滤不等于的code
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<SyscodeVO> doFindSyscodeVOByType(String type, int[] neCode)
			throws Exception {
		Criteria criteria = DAOFactory.getInstance().getSessionFactory()
				.getCurrentSession().createCriteria(SyscodeVO.class)
				.add(Restrictions.eq("type", type));
		int size = neCode.length;
		for (int i = 0; i < size; i++) {
			criteria.add(Restrictions.ne("code", neCode[i]));
		}
		return criteria.list();
	}

	/**
	 * 查询所有type信息,包括kind='*'
	 * 
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<SyscodeVO> doFindSyscodeVOByTypeAll(String type)
			throws Exception {
		return DAOFactory.getInstance().getSessionFactory().getCurrentSession()
				.createCriteria(SyscodeVO.class)
				.add(Restrictions.eq("type", type)).list();
	}

	/**
	 * 根据type和kind查找SyscodeVO对象
	 * 
	 * @param type
	 * @param kind
	 * @return
	 * @throws Exception
	 */
	@Override
	public SyscodeVO doFindSyscodeVOByTypeAndKind(String type, String kind)
			throws Exception {
		List<SyscodeVO> list = DAOFactory.getInstance().getSessionFactory()
				.getCurrentSession().createCriteria(SyscodeVO.class)
				.add(Restrictions.eq("type", type))
				.add(Restrictions.eq("kind", kind)).list();
		if (null != list && list.size() > 0)
			return list.get(0);
		return null;
	}

	/**
	 * 根据type查找记录数
	 * 
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@Override
	public int doCountByType(String type) throws Exception {
		Criteria criteria = DAOFactory.getInstance().getSessionFactory()
				.getCurrentSession().createCriteria(SyscodeVO.class)
				.add(Restrictions.eq("type", type))
				.setProjection(Projections.rowCount());
		Object result = criteria.uniqueResult();
		if (result instanceof Long) {
			return ((Long) result).intValue();
		} else {
			return (Integer) criteria.uniqueResult();
		}
	}

}
